package com.studyyoun.demoandroidapplication;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import io.flutter.embedding.android.FlutterFragment;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;

public class FlutterFragmentActivity extends AppCompatActivity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_flutter_fragment);
		
		function2();
		
	}
	
	private void function1() {
		// 获取到NewEngineFragmentBuilder对象
		FlutterFragment.NewEngineFragmentBuilder lBuilder = FlutterFragment.withNewEngine();
		//指定初始路由
		lBuilder.initialRoute("route1");
		//获取FlutterFragment
		FlutterFragment flutterFragment = lBuilder.build();
		//加载页面
		getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.fl_container, flutterFragment)
				.commit();
	}
	
	/**
	 * 每次都是创建一个新的FlutterEngine对象来显示Flutter UI，
	 * 但是从官方文档中我们可以了解到每个FlutterEngine对象
	 * 在显示出Flutter UI之前是需要一个warm-up（不知道能不能翻译为预热）期的，
	 * 这会导致屏幕呈现短暂的空白，解决方式就是预先创建并启动FlutterEngine，
	 * 完成warm-up过程，然后将这个FlutterEngine缓存起来，
	 * 之后使用这个FlutterEngine来显示出Flutter UI
	 */
	private void function2() {
		// 创建可缓存的FlutterEngine对象
		FlutterEngine flutterEngine = new FlutterEngine(this);
		//指定初始路由
		flutterEngine.getNavigationChannel().setInitialRoute("route1");
		flutterEngine.getDartExecutor().executeDartEntrypoint(
				DartExecutor.DartEntrypoint.createDefault()
		);
		/**
		 * 将FlutterEngine缓存起来，这里传入的"my_engine_id"就相当于缓存名称
		 */
		FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine);
		
		/**
		 * 创建FlutterFragment，参数传入上面的缓存名称
		 * withCachedEngine()方法返回的是一个CachedEngineFragmentBuilder对象，
		 */
		FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
				.build();
		getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.fl_container, flutterFragment)
				.commit();
	}
}